//
//  AppointmentSrollView.swift
//  puretennis
//
//  Created by IYE Technologies on 1/15/15.
//  Copyright (c) 2015 IYE Technologies. All rights reserved.
//

import UIKit


enum ContainerType : Int{
    case Invitees;
    case Participants;
    case Requests;
}

class AppointmentScrollView: UIScrollView {
    
    var appointmentGuid:String!;
    
    var ownerGuid:String!;
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder);
    }
    
    override init() {
        super.init();
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame);
        self.layer.masksToBounds = true;
        self.layer.cornerRadius = 4;
        self.layer.borderColor = UIColor.whiteColor().CGColor;
        self.layer.borderWidth = 0.5;
        self.contentSize.width = NormalView.margin();
    }

    func addElements(appointmentGuid:String,ownerGuid:String,elements:[NSDictionary],dropTargetView:AppointmentScrollView?,type:ContainerType){
        self.appointmentGuid = appointmentGuid;
        self.ownerGuid = ownerGuid;
        for element in elements{
            self.moveInto(element, type: type, dropTargetView: dropTargetView);
        }
    }
    
    func dropedElement(element:NSDictionary,type:ContainerType){
        var requestGuid = element.objectForKey("guid") as String;
        var url = "/api/v1/appointment/request/accept/\(requestGuid)";
        HttpUtils.sendSynchronousRequest(url, method: RequestMethod.GET, requestBody: nil);
        self.moveInto(element, type: type,dropTargetView: nil);
        self.moveScrollToEndPostion();
    }
    
    func moveInto(element:NSDictionary,type:ContainerType,dropTargetView:AppointmentScrollView?){
        var view:NormalView!;
        var currentUserGuid = Utils.currentUserGuid();
        if(dropTargetView != nil && (currentUserGuid == self.ownerGuid)){
            view = DragableView(containerView: self,dropTargetView: dropTargetView,element: element,type: type,ownerGuid: ownerGuid);
        } else {
            view = NormalView(containerView: self, element: element,type: type,ownerGuid:ownerGuid);
        }
        self.addSubview(view);
    }
    
    func moveScrollToEndPostion(){
        var offset = (self.contentSize.width - self.frame.width);
        if(offset > 0){
            self.setContentOffset(CGPoint(x: offset, y: 0), animated: true);
        }
    }
    
    func adjustSubviews(){
        var subviews = self.subviews;
        var margin = NormalView.margin();
        var lastX:CGFloat = margin;
        self.contentSize.width = margin;
        for subview in subviews{
            if(!(subview is NormalView)){
                continue;
            }
            var normalView = (subview as NormalView);
            
            UIView.animateWithDuration(0.3, animations: { () -> Void in
                normalView.frame.origin.x = lastX;
            });
            
            normalView.originalFrame.origin.x = lastX;
            lastX += normalView.frame.width + margin;
            self.contentSize.width = lastX;
        }
   }
    
    func readyingChoice(){
        var subviews = self.subviews;
        for subview in subviews{
            if(subview is NormalView){
                var view = subview as NormalView;
                view.readyingChoice();
            }
        }
    }
    
    func cancelChoice(){
        var subview = self.subviews;
        for subview in subviews{
            if(subview is NormalView){
                var view = subview as NormalView;
                view.cancelChoice();
            }
        }
    }

    
    func cancelInvitation(){
        var subviews = self.subviews;
        for subview in subviews{
            if(subview is NormalView){
                var view = subview as NormalView;
                if(view.chosen){
                    var element = view.element;
                    var guid = element.objectForKey("guid") as String;
                    Utils.debug("Cancel invitation by guid [\(guid)]");
                    var url = "/api/v1/appointment/invitation/cancel/\(guid)";
                    HttpUtils.sendSynchronousRequest(url, method: RequestMethod.GET, requestBody: nil);
                    view.removeFromSuperview();
                    self.adjustSubviews();
                }
            }
        }
    }
    
    func removeFromPanticipantsList(){
        var subviews = self.subviews;
        for subview in subviews{
            if(subview is NormalView){
                var view = subview as NormalView;
                if(view.chosen){
                    var element = view.element;
                    var user:NSDictionary!;
                    switch (view.type!) {
                    case .Invitees:
                        user = element.objectForKey("invitee") as NSDictionary;
                        break;
                    case .Participants:
                        user = element.objectForKey("user") as NSDictionary;
                        break;
                    default:
                        user = element.objectForKey("sender") as NSDictionary;
                        break;
                    }
                    var userGuid = user.objectForKey("guid") as String;
                    self.leaveAppointment(userGuid,moveOutView: view);
                }
            }
        }
    }
    
    func leaveAppointment(userGuid:String,moveOutView:NormalView?){
        Utils.debug("Remove participant by guid [\(userGuid)]");
        var url = "/api/v1/appointment/participants/remove";
        var postData = NSMutableDictionary();
        postData.setObject(self.appointmentGuid, forKey: "appointmentGuid");
        postData.setObject(userGuid, forKey: "participantGuid");
        HttpUtils.sendSynchronousRequest(url, method: RequestMethod.POST, requestBody: postData);
        self.moveOut(userGuid, moveOutView: moveOutView);
    }
    
    func moveOut(userGuid:String,moveOutView:NormalView?){
        if(moveOutView == nil){
            var subviews = self.subviews;
            for subview in subviews{
                if(subview is NormalView){
                    var view = subview as NormalView;
                    var element = view.element;
                    var user:NSDictionary!;
                    switch (view.type!) {
                    case .Invitees:
                        user = element.objectForKey("invitee") as NSDictionary;
                        break;
                    case .Participants:
                        user = element.objectForKey("user") as NSDictionary;
                        break;
                    default:
                        user = element.objectForKey("sender") as NSDictionary;
                        break;
                    }
                    var guid = user.objectForKey("guid") as String;
                    if(userGuid == guid){
                        view.removeFromSuperview();
                    }
                }
            }
        } else {
            moveOutView?.removeFromSuperview();
        }
        self.adjustSubviews();
    }
    
    func rejectRequest(){
        var subviews = self.subviews;
        for subview in subviews{
            if(subview is NormalView){
                var view = subview as NormalView;
                if(view.chosen){
                    var element = view.element;
                    var requestGuid = element.objectForKey("guid") as String;
                    Utils.debug("Remove request by guid [\(requestGuid)]");
                    var url = "/api/v1/appointment/request/reject/\(requestGuid)";
                    HttpUtils.sendSynchronousRequest(url, method: RequestMethod.GET, requestBody: nil);
                    view.removeFromSuperview();
                    self.adjustSubviews();
                }
            }
        }
    }
    
    func acceptJoinRequest(){
        var subviews = self.subviews;
        for subview in subviews{
            if(subview is DragableView){
                var view = subview as DragableView;
                if(view.chosen){
                    view.moveToTargetView()
                }
            }
        }
       
    }
    
    func acceptInvitation(targetView:AppointmentScrollView){
        var subviews = self.subviews;
        for subview in subviews{
            if(subview is NormalView){
                var view = subview as NormalView;
                var isMe = view.isMe()
                if(isMe){
                    var url = "/api/v1/appointment/accept";
                    var httpBody = NSMutableDictionary();
                    httpBody.setObject(self.appointmentGuid, forKey: "guid");
                    HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: httpBody, successHandle: { (response) -> Void in
                        var element = view.element;
                        view.removeFromSuperview();
                        targetView.moveInto(element, type: ContainerType.Invitees,dropTargetView: nil);
                        targetView.moveScrollToEndPostion();
                        self.adjustSubviews();
                        }, errorHandle: { (error) -> Void in
                            
                    });
                }
            }
        }
    }
  }
